var request = require('request').defaults({
    json: true
});
var q = require('q');
var redis = require('redis');
var config = require('../config.json');
var basicHelper = {
    //从缓存中获取线路列表
    _getLineList: function(prjTypeCode) {
        var type = prjTypeCode || 'MetroMonitor';
        var redisKey = config.redisNamespace + ":" + type.charAt(0).toLowerCase() + type.slice(1);
        var client = redis.createClient();
        var defer = q.defer();
        client.get(redisKey, function(err, reply) {
            if (!err) {
                while (typeof(reply) === 'string') {
                    reply = JSON.parse(reply);
                }
                client.quit();
                defer.resolve(reply);
            } else {
                client.quit();
                defer.resolve([]);
            }
        });
        return defer.promise;
    },
    //从线路中找到Prj
    _findProject: function(lineList, prjId) {
        for (var i = 0; i < lineList.length; i++) {
            for (var j = 0; j < lineList[i].projects.length; j++) {
                if (lineList[i].projects[j].prjId === prjId) {
                    return {
                        lineIndex: i,
                        prjIndex: j,
                        lineList: lineList
                    };
                }
            }
        }
        return null;
    },
    //从服务器拉取最新的线路列表
    _refreshRedisCache: function(type) {
        var url = config.authorUrl;
        var defer = q.defer();
        request({
            method: 'get',
            url: url + '/refreshProjects/' + type
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                defer.resolve();
            } else {
                defer.resolve();
            }
        });
        return defer.promise;
    },
    //如果找到了Prj,则直接更新Redis中的数据
    _updateRedisCache: function(lineListInfo, params) {
        if (lineListInfo) {
            if (params) {
                var prj = lineListInfo.lineList[lineListInfo.lineIndex].projects[lineListInfo.prjIndex];
                prj[params.property] = params.value;
            }
            return lineListInfo.lineList;
        } else {
            return null;
        }

    },
    //将更改后的数据重新存入Redis
    _saveIntoRedis: function(type, lineList) {
        if (lineList) {
            var redisClient = redis.createClient();
            var redisKey = config.redisNamespace + ":" + type.charAt(0).toLowerCase() + type.slice(1);
            redisClient.set(redisKey, JSON.stringify(lineList), redis.print);
            redisClient.quit();
        }
    }
};

var helper = {
    //将整个流程组合打包
    //刷新redis缓存,如果缓存中已有该项目则更新该项目属性,否则从服务器拉取最新的列表
    updateRedisCache: function(prjTypeCode, prjId, data) {
        var defer = q.defer();
        basicHelper._getLineList(prjTypeCode)
            .then(function(lineList) {
                var prjInfo = basicHelper._findProject(lineList, prjId);
                return prjInfo;
            }).then(function(info) {
                if (info) {
                    //如果缓存中存在,更新项目属性,较快
                    return basicHelper._updateRedisCache(info, data);
                } else {
                    //如果缓存中不存在,刷新整个缓存,较慢
                    return basicHelper._refreshRedisCache(prjTypeCode);
                }
            }).then(function(lineList) {
                basicHelper._saveIntoRedis(prjTypeCode, lineList);
                defer.resolve();
            });
        return defer.promise;
    }
};
module.exports = helper;
